import { createRouter } from '@gowiny/uni-router'
import PAGE_DATA from '@/pages.json'
import pinia from '@/store'
import { isNull } from '@/utils'

const router = createRouter({
  pageData: PAGE_DATA
})
const pageSetting = []
PAGE_DATA.pages.forEach(item => {
  pageSetting['/' + item.path] = item
})

const neesLogin = function (path) {
  const page = pageSetting[path]
  return isNull(page.needLogin) ? false : page.needLogin
}

const loginFirst = false
router.beforeEach((to, from) => {
  console.log('beforeEach', to, from)
  if (isNull(pinia.userStore.userInfo)) {
    // 不是默认页或者登录页，并且需要登录则进行登录
    if (to.path !== '/pages/loginPage/loginPage' && (loginFirst || neesLogin(to.path))) {
      const userInfo = pinia.userStore.getUserInfo()
      if (isNull(userInfo)) {
        return {
          to: { // 需要跳转的新页面
            path: '/pages/loginPage/loginPage'
          },
          navType: 'push'// 跳转方式

        }
      }
    }
  }
})

export default router
